﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WmWebSystem.Models;
using WmWebSystem.Service;
using WmWebSystem.DbHelper;

namespace WmWebSystem.Controllers
{
    public class NewsController : Controller
    {
        //
        // GET: /News/

        WmDb mydb = new WmDb();


        [Authorize(Roles = "admin,editer")]
        public ActionResult Index()
        {
            WmWebSystem.Models.MvcPage Model = new MvcPage();
            Model.CurrentPageIndex = 1;  //当前页 默认第一页

            int SkinCount = (Model.CurrentPageIndex - 1) * Model.PageSize;

            //测试用例。实际用自己的逻辑获取数据
            List<News> datesource = GetDataSource();//要分页的数据源
            Model.NewsList = datesource.Where(r => r.NewsId >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            //测试用例。实际用自己的逻辑获取数据

            //是否开启Ajax分页
            Model.IsAjax = true;
            Model.TotalCount = datesource.Count;//获取记录总数

            //获取分页数据
            Model.NewsList = datesource.Where(r => r.NewsId >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            return View(Model);

        }

        private List<News> GetDataSource()
        {
            var news = from b in mydb.Newss
                       orderby b.AddTime ascending
                       select b;
            List<News> model = new List<News>();
            foreach (var item in news)
            {
                model.Add(item);
            }
            return model;
        }

        public ActionResult PageIndex(WmWebSystem.Models.MvcPage Model)
        {

            //分页数据源。自己写逻辑获取。


            int SkinCount = (Model.CurrentPageIndex - 1) * Model.PageSize;

            //测试用例。实际用自己的逻辑获取数据
            List<News> datesource = GetDataSource();//要分页的数据源
            Model.NewsList = datesource.Where(r => r.NewsId >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            //测试用例。实际用自己的逻辑获取数据

            Model.TotalCount = datesource.Count;//获取记录总数
            if (Request.IsAjaxRequest())  //是AJAX请求的话返回AJAX分页数据
            {
                Model.IsAjax = true;
                return View(Model);
            }
            else
            {
                Model.IsAjax = false;
                return this.PartialView("Index", Model);
            }
            //return View(Model);
        }


        public ActionResult List()
        {

            var news = NewsHelper.FindAllNewsby(1);
            return View(news.ToList());
        }

        [HttpPost]
        [Authorize(Roles = "admin,editer")]
        public ActionResult Search()
        {
            string title = Request.Form["s_title"];
            string cont = Request.Form["s_cont"];
            DateTime start, end;
            start = Convert.ToDateTime("2012-1-1");
            end = Convert.ToDateTime("2100-1-1");
            if (Request.Form["s_time"].ToString() != "")
            {
                start = Convert.ToDateTime(Request.Form["s_time"]);
            }
            if (Request.Form["e_time"].ToString() != "")
            {
                end = Convert.ToDateTime(Request.Form["e_time"]);
            }

            return View(NewsHelper.SearchNewsby(title, cont, start, end));

        }

        public ActionResult Details(int id)
        {
            var news = mydb.Newss.Find(id);
            if (news == null)
            {
                return RedirectToAction("Index");
            }
            else
            {
                UpdateTheClickNumToNewss(id);
            }
            var n1 = from n in mydb.Newss
                     where n.NewsId == id
                     select n;
            ViewData["newsDetails"] = n1;
            return View();
        }

       // [Authorize(Roles = "admin,editer")]
        public ActionResult Create()
        {
            return View();
        }

        [Authorize(Roles = "admin,editer")]
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(News model)
        {
            string type = HttpUtility.HtmlDecode(Request.Form["NewsType1"]);
            string typeName = "";
            if (type == "1")
                typeName = "News";
            else if (type == "2")
                typeName = "About";
            else
                typeName = "Other";
            int status = NewsHelper.CreateNewToNews(model.Title, model.Content, type,typeName);
            return RedirectToAction("index");
            
        }


        [Authorize(Roles = "admin,editer")]
        public ActionResult Edit(int id)
        {
            News news = mydb.Newss.Find(id);
            if (news == null)
            {
                return RedirectToAction("Index");
            }
            return View(news);
        }

        [Authorize(Roles = "admin,editer")]
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Edit(News model)
        {
            try
            {
                var news = mydb.Newss.Find(model.NewsId);
                UpdateModel(news);
                mydb.SaveChanges();
                return RedirectToAction("Details", new { id = model.NewsId });
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", "修改失败，请查看详细错误信息:" + e);
                return View(model);
            }
            
        }

        [Authorize(Roles = "admin,editer")]
        public ActionResult Delete(int id)
        {
            News news = mydb.Newss.Find(id);
            if (news == null)
                return RedirectToAction("Index");
            return View(news);
        }

        [Authorize(Roles = "admin,editer")]
        [HttpPost]
        public RedirectToRouteResult Delete(int id, FormCollection collection)
        {
            var news = mydb.Newss.Find(id);
            mydb.Newss.Remove(news);
            mydb.SaveChanges();
            return RedirectToAction("Index");
        }


        //关注新闻
        public void UpdateTheClickNumToNewss(int id)
        {
            var news = mydb.Newss.Find(id);
            news.ClickNum++;
            try
            {
                UpdateModel(news);

                mydb.SaveChanges();
                //将记录写入日志
                string p1 = "Delete a news from Newss, where NewsId:" + id;
                WriteLog.WriteSysLog(p1);
            }
            catch (FieldAccessException ex)
            {
                //失败，进行回滚操作  记录异常

                WriteLog.WriteSysLog(ex.ToString());
            }

        }



    }
}
